// components/OrderDetails.js
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Toast } from 'antd-mobile';
import styles from '../css/orderDetails.module.css';
// 图片导入
import leftImg from '../assets/left.png';
import hourse3Img from '../assets/hourse3.png';
import qrCodeImg from '../assets/qrcode.png';
import eyeImg from '../assets/hide.png';
import passImg from '../assets/shows.png';
import telImg from '../assets/tel.png';
import startoneImg from '../assets/redstar.png';
import starttwoImg from '../assets/redstar.png';
import starthreeImg from '../assets/redstar.png';
// 导入新的API服务
import { deleteOrder } from '../api/order.js';
import { imgUrl } from '../config'; // 导入imgUrl
const OrderDetails = () => {
  const navigate = useNavigate();
  const [eye, setEye] = useState(false);
  const [orderdata, setOrderdata] = useState({});
  const [data, setData] = useState([]);
  const [nickname, setNickname] = useState('');
  const [tel, setTel] = useState('');
  const [unitPrice, setUnitPrice] = useState(0);
  const [loading, setLoading] = useState(false); // 添加加载状态
  const [error, setError] = useState(null); // 添加错误状态

  // 返回上一页
  const left = () => {
    navigate(-1);
  };

  // 跳转首页
  const first = () => {
    navigate("/home");
  };

  // 初始化数据
  useEffect(() => {
    // 从sessionStorage获取数据
    const order = sessionStorage.getItem("orderid");
    const orderdata = JSON.parse(sessionStorage.getItem("orderdata"));
    const nickname = sessionStorage.getItem("nickname");
    const tel = sessionStorage.getItem("tel");
    const code = sessionStorage.getItem("code");
    const jingquData = JSON.parse(sessionStorage.getItem("jingqu"));

    setOrderdata(orderdata);
    setNickname(nickname);
    setTel(tel);
    setData(jingquData);
    
    // 计算并设置单价
    if (orderdata.total_price && orderdata.number) {
      setUnitPrice((orderdata.total_price / orderdata.number).toFixed(2));
    }
  }, []);

  // 跳转二维码页面
  const goToQRcode = () => {
    sessionStorage.setItem("QRid", orderdata.id); // 订单id
    sessionStorage.setItem("QRstatus", orderdata.status); // 订单状态
    sessionStorage.setItem("QRcode", orderdata.order_code); // 订单编号
    sessionStorage.setItem("QRnum", orderdata.number); // 商品数量
    sessionStorage.setItem("QRshopname", orderdata.name); // 商品名字
    sessionStorage.setItem("QRname", orderdata.scenic_name); // 景点名称
    sessionStorage.setItem("QRnickname", nickname); // 个人姓名
    sessionStorage.setItem("QRtel", tel); // 个人电话
    sessionStorage.setItem("QRcreate_time", orderdata.create_time); // 创建时间
    sessionStorage.setItem("QRtime", orderdata.time); // 时间
    sessionStorage.setItem("QRtotal_price", orderdata.total_price); // 订单总价
    navigate("/code");
  };

  const [jingqu, setjingqu] = useState(JSON.parse(sessionStorage.getItem("jingqu")) || []);
  console.log(jingqu);

  // 重新购买
  const suborder = () => {
    console.log(unitPrice);
    sessionStorage.setItem("numstate", false);
    sessionStorage.setItem("deata", JSON.stringify(orderdata));
    sessionStorage.setItem("unitPrice", unitPrice);
    sessionStorage.setItem("numding", orderdata.number);
    const filteredData = jingqu.filter(jingquItem => jingquItem.id === orderdata.scenic_id);
    console.log('筛选后的数据:', filteredData);
    sessionStorage.setItem("jingdata", JSON.stringify(filteredData[0]));
    navigate("/scenicdetails");
  };

  // 显示/隐藏删除确认弹窗
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

  const deletes = () => {
    setShowDeleteConfirm(true);
  };

  const cancelDelete = () => {
    setShowDeleteConfirm(false);
  };

  // 确认删除订单
  const affirmDelete = async () => {
    if (!orderdata.id) {
      Toast.show('订单ID不存在');
      return;
    }
    
    setLoading(true);
    setError(null);
    
    try {
      const response = await deleteOrder(orderdata.id);
      
      if (response.code === 1) {
        setShowDeleteConfirm(false);
        Toast.show('删除成功');
        
        // 延迟后跳转到订单列表
        setTimeout(() => {
          navigate("/orderPage");
        }, 500);
      } else {
        setError(response.msg || '删除失败');
        Toast.show(error);
      }
    } catch (err) {
      setError(err.message || '网络错误，请重试');
      Toast.show(error);
      console.error("删除订单错误:", err);
    } finally {
      setLoading(false);
    }
  };

  // 渲染星星评分
  const renderStars = (score) => {
    const stars = [];
    const fullStars = Math.floor(score);
    const hasHalfStar = score % 1 >= 0.5;

    for (let i = 1; i <= 5; i++) {
      if (i <= fullStars) {
        stars.push(<img key={i} src={starttwoImg} alt="full star" />);
      } else if (i === fullStars + 1 && hasHalfStar) {
        stars.push(<img key={i} src={starthreeImg} alt="half star" />);
      } else {
        stars.push(<img key={i} src={startoneImg} alt="empty star" />);
      }
    }

    return <div className={styles.start}>{stars}</div>;
  };

  // 添加备用复制方法
  const fallbackCopyTextToClipboard = (text) => {
    // 创建一个临时文本区域元素
    const textArea = document.createElement("textarea");
    textArea.value = text;

    // 使其不在视口中显示但仍可访问
    textArea.style.position = "fixed";
    textArea.style.top = "0";
    textArea.style.left = "0";
    textArea.style.width = "2em";
    textArea.style.height = "2em";
    textArea.style.padding = "0";
    textArea.style.border = "none";
    textArea.style.outline = "none";
    textArea.style.boxShadow = "none";
    textArea.style.background = "transparent";

    // 添加到文档中
    document.body.appendChild(textArea);

    // 选中并复制
    textArea.focus();
    textArea.select();

    try {
      const successful = document.execCommand('copy');
      if (successful) {
        Toast.show('复制成功');
      } else {
        Toast.show('复制失败，请手动复制');
      }
    } catch (err) {
      console.error('复制失败:', err);
      Toast.show('复制失败，请手动复制');
    }

    // 移除临时元素
    document.body.removeChild(textArea);
  };

  // 格式化电话号码
  const formatPhone = (phone) => {
    if (!phone) return '';
    const regPhone = /^(\d{3})\d{4}(\d{4})$/;
    return phone.trim().replace(regPhone, "$1****$2");
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '';
    const parts = dateString.split(' ');
    const dateParts = parts[0].split('-');
    return dateParts.join('-');
  };

  return (
    <div className={styles.container} style={{ backgroundColor: '#f4f4f4' }}>
      {/* 顶部导航栏 */}
      <div className={styles.top}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <div className={styles.left}>
            <img src={leftImg} alt="返回" onClick={left} />
            <div className={styles.line}></div>
            <img id={styles.hourse} src={hourse3Img} alt="首页" onClick={first} />
          </div>
        </div>
        <p>订单详情</p>
        <img style={{ width: '30px', height: '30px' }} id={styles.QRcode} src={qrCodeImg} alt="二维码" onClick={goToQRcode} />
      </div>

      {/* 订单状态 */}
      <h2 className={styles.orderStatus}>
        {orderdata.status == 1 ? "交易完成" :
          orderdata.status == 2 ? "待支付" :
            orderdata.status == 3 ? "已取消" :
              orderdata.status == 4 ? "已支付" : "已退款"}
      </h2>

      {/* 订单详情内容 */}
      <div className={styles.detailsBig}>
        <div className={styles.details}>
          <b>应付金额</b>
          <div className={styles.money}>
            <span>￥</span>
            <b id={styles.allPrice}>{orderdata.total_price || '0'}</b>
          </div>
        </div>
        <div className={styles.lines}></div>

        <div className={styles.tickets}>
          <b id={styles.name}>{orderdata.name || '未命名商品'}</b>
          <div>
            <span><span id={styles.num}>{orderdata.number || '1'}</span> x &nbsp;</span>
            <b style={{ fontSize: '15px' }}>￥</b>
            <b style={{ marginRight: '10px', fontSize: '18px' }} id={styles.unitPrice}>
              {unitPrice || '0'}
            </b>
          </div>
        </div>

        <div className={styles.font}>
          <div style={{ display: 'flex', color: '#636363' }}>
            <span style={{ marginLeft: '10px' }}>使用日期</span>
            <p style={{ marginLeft: '20px' }} id={styles.date}>
              {orderdata.create_time ? `${formatDate(orderdata.create_time)}&nbsp;至&nbsp;${orderdata.time}` : '未设置日期'}
            </p>
          </div>
        </div>

        <div className={styles.fonts}>
          <div style={{ display: 'flex', color: '#636363' }}>
            <span style={{ marginLeft: '10px' }}>单价包含</span>
            <p><span id={styles.door}>{orderdata.name || '未命名商品'}</span>包含所有景点</p>
          </div>
        </div>

        <div className={styles.liner}></div>

        <div className={styles.message}>
          <b>信息</b>
          <div style={{ display: 'flex', color: '#636363', marginTop: '5px' }}>
            <span style={{ marginLeft: '10px', fontSize: '14px' }}>游玩人</span>
            <div style={{ display: 'flex', alignItems: 'center', justifySelf: 'center' }}>
              <p style={{ marginLeft: '20px', fontSize: '14px' }} id={styles.compellation}>
                {eye ? nickname : '***'}
              </p>
              <img
                style={{ width: '20px', height: '20px', marginLeft: '10px' }}
                id={styles.eye}
                src={eye ? passImg : eyeImg}
                alt="显示/隐藏"
                onClick={() => setEye(!eye)}
              />
            </div>
          </div>

          <div style={{ display: 'flex', color: '#636363', marginTop: '5px' }}>
            <span style={{ marginLeft: '50px' }}></span>
            <div style={{ display: 'flex', alignItems: 'center', justifySelf: 'center' }}>
              <p style={{ marginLeft: '20px', fontSize: '14px' }} id={styles.phone}>
                {eye ? tel : formatPhone(tel)}
              </p>
            </div>
          </div>

          <div style={{ display: 'flex', color: '#636363', marginTop: '5px' }}>
            <span style={{ marginLeft: '50px' }}></span>
            <div style={{ display: 'flex', alignItems: 'center', justifySelf: 'center' }}>
              <p style={{ marginLeft: '20px', fontSize: '14px' }}>
                身份证号<span id={styles.idNum}>暂无</span>
              </p>
            </div>
          </div>
        </div>

        <div className={styles.liner}></div>

        <div style={{ display: 'flex', color: '#636363' }}>
          <span style={{ marginLeft: '10px', fontSize: '14px' }}>订单编号</span>
          <div style={{ display: 'flex', alignItems: 'center', fontSize: '14px' }}>
            <input
              type="number"
              readOnly
              style={{
                marginLeft: '20px',
                outline: 'none',
                width: '60px',
                paddingRight: '5px',
                border: '0'
              }}
              id={styles.code}
              value={orderdata.order_code || ''}
            />
            <textarea style={{ display: 'none' }}></textarea>
            <span
              style={{ color: '#2a82e4', marginLeft: '10px' }}
              id={styles.copyInput}
              onClick={() => {
                const textToCopy = orderdata.order_code || '';

                // 首选方法：使用现代Clipboard API
                if (navigator.clipboard) {
                  navigator.clipboard.writeText(textToCopy)
                    .then(() => {
                      Toast.show('复制成功');
                    })
                    .catch(err => {
                      console.error('复制失败:', err);
                      // 复制失败时尝试备用方法
                      fallbackCopyTextToClipboard(textToCopy);
                    });
                } else {
                  // 备用方法：使用传统的document.execCommand
                  fallbackCopyTextToClipboard(textToCopy);
                }
              }}
            >
              复制
            </span>
          </div>
        </div>

        <div style={{ display: 'flex', color: '#636363', marginTop: '5px' }}>
          <span style={{ marginLeft: '10px', fontSize: '14px' }}>交易时间</span>
          <div style={{ display: 'flex', alignItems: 'center', fontSize: '14px' }}>
            <p style={{ marginLeft: '20px' }} id={styles.time}>
              {orderdata.create_time || '未设置时间'}
            </p>
          </div>
        </div>

        <div className={styles.liner}></div>

        <div className={styles.role}>
          <b>退改规则</b>
        </div>
        <div className={styles.rreturn}>随时退</div>
        <span style={{ color: '#636363', fontSize: '14px', marginLeft: '10px' }}>
          未使用可随时申请全额退款
        </span>
        <div className={styles.rreturn}>过期退</div>
        <span style={{ color: '#636363', fontSize: '14px', marginLeft: '10px' }}>
          使用后1天经核实未使用系统将自动发起退款申请
        </span>
        <p style={{ color: '#636363', fontSize: '14px', marginLeft: '10px' }}>
          下单后不支持修改如期
        </p>

        <div className={styles.liners}></div>

        <div style={{ alignItems: 'center', justifySelf: 'center' }}>
          <div className={styles.role}>
            <b>供应商电话</b>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <span style={{
              color: '#636363',
              fontSize: '14px',
              margin: '10px 10px',
              display: 'block'
            }}>
              崔出票/协商退改
            </span>
            <div id={styles.alink}>
              <a href={`tel:${orderdata.tel || ''}`}>
                <img style={{ width: '35px', height: '35px', marginRight: '35px' }} id={styles.tel} src={telImg} alt="电话" />
              </a>
            </div>
          </div>
        </div>
      </div>

      {/* 推荐景区 */}
      <div className={styles.like}>
        <div></div>
        <b>更多景区等你打卡</b>
        <div></div>
      </div>

      {/* 景区列表 */}
      <div className={styles.item}>
        {data.slice(0, 3).map((item, i) => (
          <div key={i} className={styles.libVideo} onClick={() => details(item, i, navigate)}>
            <img src={`${imgUrl}${item.img}`} alt={item.name} />
            <div className={styles.content}>
              <b>{item.name}</b>
              <div className={styles.twoBlock}>
                <p className={styles.play}>游玩榜</p>
                <p className={styles.new}>新乡&nbsp;景区榜第1名</p>
              </div>
              <div className={styles.allstart}>
                {renderStars(item.score || 0)}
                <div className={styles.startText}>
                  <span>{item.score || '0'}分</span>
                  <p>1000条评价</p>
                </div>
              </div>
              <span id={styles.distance} style={{ marginLeft: '6px' }}>距离你26km</span>
              <div className={styles.today}>
                <p>可订明日</p>
                <div className={styles.door}>
                  <p>门票</p>
                  <span>￥</span>
                  <b>80</b>
                  <p style={{ marginLeft: "-5px" }}>起</p>
                </div>
              </div>
              <div className={styles.player}>
                {item.must && (
                  <>
                    <b>必玩</b>•<span>{item.must}</span>
                  </>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* 底部提示 */}
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        fontSize: '14px',
        color: '#636363',
        width: '100%',
        height: '70px',
        marginBottom: '45px',
        zIndex: '-1',
        position: 'relative'
      }}>
        <span>没有更多了...</span>
      </div>

      {/* 底部操作栏 */}
      <div className={styles.bottom}>
        <div className={styles.del} onClick={deletes}>
          删除订单
        </div>
        <div className={styles.suborder} onClick={suborder}>
          重新购买
        </div>
      </div>

      {/* 删除确认弹窗 */}
      {showDeleteConfirm && (
        <div className={styles.deleteModalOverlay}>
          <div className={styles.deleteModal}>
            <div className={styles.modalContent}>
              <h3>确认删除</h3>
              <p>确定要删除该订单吗？此操作不可恢复。</p>
              <div className={styles.modalButtons}>
                <button
                  className={styles.cancelButton}
                  onClick={cancelDelete}
                >
                  取消
                </button>
                <button
                  className={styles.confirmButton}
                  onClick={affirmDelete}
                  disabled={loading}
                >
                  {loading ? '删除中...' : '确认删除'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 跳转景区详情 - 已修复
const details = (item, index, navigate) => {
  sessionStorage.setItem("jingid", item.id);
  sessionStorage.setItem("jingdata", JSON.stringify(item));
  navigate("/scenicdetails");
};

export default OrderDetails;